import json
import sqlite3
import paho.mqtt.client as mqtt

import  multiprocessing
# MQTT服务器地址

from Mqtt.volumes import thread_post

import threading
import time
from tools.logger import log
from concurrent.futures import ThreadPoolExecutor
import threading
import queue
import time
import  os



# MQTT代理服务器地址和端口

MQTT_SERVER  = "172.16.1.29"
MQTT_PORT= 18832
username = "intranet"
password = "gst@2024_123!"
topic = "IOT/intranet/client/request/prod/#"
publish_topic = "IOT/intranet/server/report/prod/"
# 全局退出标志
keep_running = True

# 定义全局退出标志
stop_event = threading.Event()

# 共享队列（线程安全）
param_queue = queue.Queue()
param_queue1 = queue.Queue()
param_queue2 = queue.Queue()
param_queue3 = queue.Queue()
# 回调函数：当客户端收到消息时调用

def on_message(client, userdata, message):


    print("等待接收已订阅的下发体信息")
    #订阅到设备，接收下发到设备的下发体，获取publishId
    print(f"Received message: {message.payload.decode()} on topic: {message.topic}")

    TOPIC =  f'{message.topic}'   #topic
    param_queue.put(TOPIC)  # 参数放入队列

    message = json.loads(message.payload.decode())
    publishid = message['publishId']
    #print(f"生成参数publishid: ",publishid)
    param_queue1.put(publishid)  # 参数放入队列

    imei = message['imei']
    param_queue2.put(imei)  # 参数放入队列

    cmd = message['cmd']
    param_queue3.put(cmd)  # 参数放入队列








# 回调函数：当客户端成功连接到MQTT服务器时调用
def on_connect(client, userdata, flags, rc):
  if rc == 0:
    print("成功连接到MQTT代理！")
    # 批量订阅10个主题
    result,mid = client.subscribe(topic)
    print("Subscribed: result=%s, mid=%s" % (result, mid))

  else:
    print(f"连接失败，错误码：{rc}")








def  callback():
  #获取回调信息
  # 向同一 Topic
  client = mqtt.Client()
  client.username_pw_set(username=username, password=password)
  client.connect(MQTT_SERVER, MQTT_PORT, 60)  # 60秒内保持连接尝试
  client.on_connect = on_connect
  # 订阅
  client.subscribe(topic)
  try:
    while keep_running:
    #while  True :
      try:
        param = param_queue.get(timeout=1)
        publishid = param_queue1.get(timeout=1)
        imei = param_queue2.get(timeout=1)
        cmd = param_queue3.get(timeout=1)
        #发布的topic
        pub_topic = f"{publish_topic}{imei}"

        mess = {"cmd": cmd, "imei": imei, "publishId": publishid, "result": "success", "resultId": 1,"topic": param}
        #client.publish(param, json.dumps(json.dumps(mess)))
        log.info(f"模拟回调信息为:{mess}")
        client.publish(pub_topic, json.dumps(json.dumps(mess)))
      except queue.Empty:
        continue  # 超时后检查keep_running
      except Exception as e:
        log.error(f"处理消息出错: {e}")
  finally:
      param_queue.task_done()
      param_queue1.task_done()
      param_queue2.task_done()
      param_queue3.task_done()

        #if pub_topic is None:  # 终止信号
            #break
       #time.sleep(0.1)  # 模拟处理耗时
      """
        param_queue.task_done()
        param_queue1.task_done()
        param_queue2.task_done()
        param_queue3.task_done()
      """





def main():

  # 创建MQTT客户端实例
  client = mqtt.Client()
  client.username_pw_set(username=username, password=password)
  # 设置回调函数
  client.on_connect = on_connect
  client.on_message = on_message


  # client.publish(topic, message)
  # 连接MQTT服务器
  client.connect(MQTT_SERVER, MQTT_PORT, 60)  # 60秒内保持连接尝试
  # 保持网络连接，并处理网络消息循环
  client.loop_start()



  #01——停止播放
  thread_post.audiostop_post()

  # 启动线程
  ##gen_thread = threading.Thread(target=on_message)
  proc_thread = threading.Thread(target=callback)
  ##gen_thread.start()
  proc_thread.start()
  # 等待生成完成
  #gen_thread.join()
  #proc_thread.join()

  print("------------------------------------01_audiostop_success------------------------------------------------")


  #02——打开继电器
  thread_post.relay_post()
  # 启动线程
  ##gen_thread1 = threading.Thread(target=on_message)
  ##proc_thread1 = threading.Thread(target=callback)
  ##gen_thread1.start()
  ##proc_thread1.start()
  # 等待生成完成
  #gen_thread.join()
  #proc_thread.join()

  print("------------------------------------02_relay_success------------------------------------------------")

  #03-调节音量
  thread_post.volume_post()
  # 启动线程
  ##gen_thread2 = threading.Thread(target=on_message)
  ##proc_thread2 = threading.Thread(target=callback)
  ##gen_thread2.start()
  ##proc_thread2.start()

  #keep_running = False  # 先设置退出标志


  #gen_thread.join()
  #proc_thread.join()

  print("MQTT client disconnected gracefully.")
  # 等待生成完成
  ##gen_thread.join(timeout=1)
  ##proc_thread.join(timeout=1.5)
  keep_running = False  # 通知 callback() 线程退出
  proc_thread.join(timeout=3)
  client.disconnect()
  """
  client.disconnect()  # 发送DISCONNECT包
  time.sleep(1)  # 等待1秒确保断开包发送
  client.loop_stop()  # 停止网络循环
  """
  print("------------------------------------03_volume_success------------------------------------------------")
  print("当前标志状态：",keep_running)




